
const voListD = []
let myDatas={
    consumerNotice:'',
    remark:''
}
const myRemoveLayui = function (obj) {
    //加删除的id
    let item = $(obj).parent()
    voListD.push({
        name: $(item).find("input[myid='one']").val(),
        price: $(item).find("input[myid='two']").val(),
        originalPrice: $(item).find("input[myid='three']").val(),
        groupPrice: $(item).find("input[myid='four']").val(),
        id: $(item).find("input[myid='five']").val(),
        isDelete: '12'
    })


    $(obj).parent().remove();
}
const addLayuiItems = () => {
    let str = `
						<div class="layui-form-item" style="display: flex;">
                            <div class="layui-inline" style="width: calc((100% - 40px) / 4);">
                                <label class="layui-form-label required">商品规格</label>
                                <div class="layui-input-block">
                                    <input class="form-control " myid="one" type="text" placeholder="请输入商品规格">
                                </div>
                            </div>
                            <div class="layui-inline" style="width: calc((100% - 40px) / 4);">
                                <label class="layui-form-label required">商品单价</label>
                                <div class="layui-input-block">
                                    <input class="form-control " myid="two" type="text" placeholder="请输入商品单价" onkeyup="restrictInput(event)">
                                </div>
                            </div>
                            <div class="layui-inline" style="width: calc((100% - 40px) / 4);">
                                <label class="layui-form-label required">商品原价</label>
                                <div class="layui-input-block">
                                    <input class="form-control " myid="three" type="text" placeholder="请输入商品原价" onkeyup="restrictInput(event)">
                                </div>
                            </div>
                            <div class="layui-inline" style="width: calc((100% - 40px) / 4);">
                                <label class="layui-form-label required">拼团价格</label>
                                <div class="layui-input-block">
                                    <input class="form-control " myid="four" type="text" placeholder="请输入拼团价格" onkeyup="restrictInput(event)">
                                    <input value="" myid="five" style="display: none">
                                </div>
                            </div>
							<button  class="layui-inline layui-btn myremove1" type="button" onclick="myRemoveLayui(this)">删除</button>
                        </div>
	`
    $('#LayuiItems').append(str)
}


$("body").on('click', '.remove', function () {
    $(this).parents('.newSet').remove();
})

layui.use(['form', 'xmSelect', 'upload', 'laydate'], function () {
    var form = layui.form;
    var layer = layui.layer, laydate = layui.laydate;
    var xmSelect = layui.xmSelect, upload = layui.upload;
    var loading;
    let datas = [],myDataList;


    $('#prodTypeId').attr("disabled",true);
    AjaxGet( '/jzweb/jazProdType/selProdType'  ).then(function (response){
        if(response.code=='0'){
            myDataList=response.data
            //设置select
            $('#prodTypeId').empty();
            $('#prodTypeId').append($('<option>', {
                value: '',
                text: '请选择商品类型'
            }))
            myDataList.forEach(item=>{
                $('#prodTypeId').append($('<option>', {
                    value: item.id,
                    text: item.name,
                    selected:$('#prodTypeIdValue').val()==item.id
                }))
            })
            $('#prodTypeId').attr("disabled",false);
            form.render('select');
            // selectInput($('#prodTypeId'),10)
        }
    }).catch(error => {
        layer.msg(error.msg)
    })



    setWangeditor('#editor-consumerNotice','#toolbar-consumerNotice',$('#consumerNotice').val(),'请输入消费须知',function onchange(editor){
        myDatas.consumerNotice = editor.getHtml()
    },null,$("#inputType").val() == 'info')
    setWangeditor('#editor-remark','#toolbar-remark',$('#remark').val(),'请输入商品详情',function onchange(editor){
        myDatas.remark = editor.getHtml()
    },null,$("#inputType").val() == 'info')


    form.on('switch(switchTest)', function (data) {
        $('#homeSort').prop('disabled', !this.checked);
        $('#homeSort').val(!this.checked?'':$('#homeSort').val())
    })

    let myStartDate,myEndDate;
        myStartDate=laydate.render({
            elem: "#startTime",
            trigger: 'click',
            type: 'datetime',
            max:"9999-12-31 24:50:14",
            done: function (value, dates) {
                myEndDate.config.min ={
                    year:dates.year,
                    month:dates.month-1, //关键
                    date: dates.date,
                    hours: dates.hours,
                    minutes: dates.minutes,
                    seconds : dates.seconds
                };
            }
        });
        myEndDate=laydate.render({
            elem: "#endTime",
            trigger: 'click',
            type: 'datetime',
            min:"1888-01-01 00:00:00",
            done: function (value, dates) {
                myStartDate.config.max={
                    year:dates.year,
                    month:dates.month-1,//关键
                    date: dates.date,
                    hours: dates.hours,
                    minutes: dates.minutes,
                    seconds : dates.seconds
                }
            }
        });

       // laydate.render({
       //      elem: "#validTime",
       //      trigger: 'click',
       //      type: 'datetime',
       //  });

    form.on('radio(demo-radio-filter)', function (data) {

        if (data?.elem?.value == '2') {
            $('#refuseReason').show()
        } else {
            $('#refuseReason').hide()
            $("textarea[name='refuseReason']").val('');
        }

    });

    //同时绑定多个元素，并将属性设定在元素上
    upload.render({
        elem: '.uploadSend'
        , multiple: 'true'
        , accept: 'images '
        , acceptMime: 'image/*'
        , before: function () {
            loading = layer.load({
                type: 3,
                content: '加载中...',
            });//在post之前定义loading
        }
        , done: function (res) {
            layer.close(loading);
            if (res.code == 0) {
                let that = this;
                changBackfill(res, that);
            } else {
                layer.msg('上传失败,请检查');
            }

        }
        , error: function (res) {
            layer.msg(res.msg)
        }
    })

    if ($('#inputType').val() != 'info') {
        //自定义验证规则
        form.verify({
            name: function (value, item) {
                if (!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)) {
                    return '商品名称不能有特殊字符';
                }
                if (/(^\_)|(\__)|(\_+$)/.test(value)) {
                    return '商品名称首尾不能出现下划线\'_\'';
                }
            },
            peopleNum: function (value, item) {
                if (null == value || '' == value) {
                    return '请输入拼团人数';
                }
            },
            validTime: function (value, item) {
                if (null == value || '' == value) {
                    return '请输入有效期';
                }
            },
            // projectId: function (value, item) {
            //     if (null == value || '' == value) {
            //         return '请输选择';
            //     }
            // },
            countDown: function (value, item) {
                if (null == value || '' == value) {
                    return '请输入倒计时';
                }
            },
            startTime: function (value, item) {
                if (null == value || '' == value) {
                    return '请输入拼团开始时间';
                }
            },
            endTime: function (value, item) {
                if (null == value || '' == value) {
                    return '请输入拼团结束时间';
                }
            },
            consumerNotice: function (value, item) {
                if (null == value || '' == value) {
                    return '请输入消费须知';
                }
            },
            guarantee: function (value, item) {
                if (null == value || '' == value) {
                    return '请输入服务保障';
                }
            },
            commodityType: function (value, item) {
                if (null == value || '' == value) {
                    return '请选择商品类型';
                }
            },
        });
    }
    //提交事件
    form.on('submit(submit)', function (data) {
        let params = data.field
        params.consumerNotice=myDatas.consumerNotice
        params.remark=myDatas.remark
        if ($('#inputType').val() != 'info') {
            if ('' == params.validTime) {
                layer.msg('请输入有效期')
                return false
            }
            if ('' == params.countDown) {
                layer.msg('请输入倒计时')
                return false
            }
            if ('' == params.startTime) {
                layer.msg('请输入拼团开始时间')
                return false
            }
            if ('' == params.endTime) {
                layer.msg('请输入拼团结束时间')
                return false
            }
            if ('' == params.consumerNotice) {
                layer.msg('请输入消费须知')
                return false
            }
            if ('' == params.guarantee) {
                layer.msg('请输入服务保障')
                return false
            }
            if ('' == params.image) {
                layer.msg('请上传商品封面')
                return false
            }
            if ('' == params.picture) {
                layer.msg('请上传商品图片')
                return false
            }
            if ('' == params.infoUrl) {
                layer.msg('请上传商品详情图')
                return false
            }
        }
        params.validTime=Number(null==params.validTime||params.validTime==''?0:params.validTime)
        let mylayuiItems = $('#LayuiItems').find('.layui-form-item')
        let voList = []
        for (let i = 0; i < mylayuiItems.length; i++) {
            let item = $(mylayuiItems[i])
            if ($('#inputType').val() != 'info') {
                if ('' == $(item).find("input[myid='one']").val()) {
                    layer.msg(`请在商品规格中输入第${i + 1}个商品规格`)
                    return false
                }
                if ('' == $(item).find("input[myid='two']").val()) {
                    layer.msg(`请在商品规格中输入第${i + 1}个商品单价`)
                    return false
                }
                if ('' == $(item).find("input[myid='three']").val()) {
                    layer.msg(`请在商品规格中输入第${i + 1}个商品原价`)
                    return false
                }
                if ('' == $(item).find("input[myid='four']").val()) {
                    layer.msg(`请在商品规格中输入第${i + 1}个拼团价格`)
                    return false
                }
            }
            voList.push({
                name: $(item).find("input[myid='one']").val(),
                price: $(item).find("input[myid='two']").val(),
                originalPrice: $(item).find("input[myid='three']").val(),
                groupPrice: $(item).find("input[myid='four']").val(),
                id: $(item).find("input[myid='five']").val()

            })
        }
        if (voListD.length > 0 && $("#inputType").val() != 'add') {
            params.voList = [...voList, ...voListD]
        } else {
            params.voList = [...voList]
        }
        delete params.file
        if ($('#inputType').val() == 'add' || $('#inputType').val() == 'edit') {
            //装换
            params.isShow = typeof params.isShow =='undefined' || params.isShow == 'no' ? 0 : 1
            if ($('#inputType').val() == 'edit') {
                params.id = $('#userId').val()
            }
            if (1 == params.isShow && params.homeSort=="") {
                layer.msg('请输入首页优先级')
                return false
            }
            AjaxPost($('#inputType').val() == 'add' ? '/jzweb/jazGroupProd/saveGroupProd' : '/jzweb/jazGroupProd/updateGroupProd', params).then(function (response) {
                parent.layer.msg("操作成功");
                var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                parent.layer.close(index);
                parent.load();
            }).catch(error => {
                layer.msg(error.msg)
            })
        } else if ($('#inputType').val() == 'info') {
            if(null==params.checkStatus){
                var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);
                parent.load();
                return false;
            }

            if( params.checkStatus+""=="2" &&  params.checkResult==''){
                layer.msg("请输入拒绝原因")
                return false
            }
            AjaxGet('/jzweb/jazGroupProd/checkGroup', {
                id: $('#userId').val(),
                state: params.checkStatus,
                result: params.checkStatus == 1 ? '' : params.checkResult
            }).then(function (response) {
                parent.layer.msg("操作成功");
                var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                parent.layer.close(index);
                parent.load();
            }).catch(error => {
                layer.msg(error.msg)
            })
        }

    });

});
let image =$("input[name='image']").val()==''||$("input[name='image']").val()==undefined?[]:$("input[name='image']").val().split(','),
    picture = $("input[name='picture']").val()==''||$("input[name='picture']").val()==undefined?[]:$("input[name='picture']").val().split(','),
    infoUrl=$("input[name='infoUrl']").val()==''||$("input[name='infoUrl']").val()==undefined?[]:$("input[name='infoUrl']").val().split(',')

function changBackfill(res, obj) {

    if (obj.id == 'image') {
        if (image.length < obj.number) {
            image.push(res.data);
            $("#" + obj.id).prepend(`
					<div class="layui-inline mybutton" style="padding: 0">
						<img class="upImg" onclick="photosClick()" src="${res.data}" style="height: 100%;width: 100%">
						<img class="closeUpload" data-index="${image?.length - 1}" src="/img/close.png" data-id="image">
					</div>
					`)


            $("input[name='image']").val(image.join(','));
        } else {
            layer.msg('上传的图片已达上限，请删除在传')
        }
    }

    if (obj.id == 'picture') {
        if (picture.length < obj.number) {
            picture.push(res.data);
            $("#" + obj.id).prepend(`
					<div class="layui-inline mybutton" style="padding: 0">
						<img class="upImg" onclick="photosClick()" src="${res.data}" style="height: 100%;width: 100%">
						<img class="closeUpload" data-index="${picture?.length - 1}" src="/img/close.png" data-id="picture">
					</div>
					`)
            $("input[name='picture']").val(picture.join(','));
        } else {
            layer.msg('上传的图片已达上限，请删除在传')
        }
    }
    if (obj.id == 'infoUrl') {
        if (infoUrl.length < obj.number) {
            infoUrl.push(res.data);
            $("#" + obj.id).prepend(`
					<div class="layui-inline mybutton" style="padding: 0">
						<img class="upImg" onclick="photosClick()" src="${res.data}" style="height: 100%;width: 100%">
						<img class="closeUpload" data-index="${infoUrl?.length - 1}" src="/img/close.png" data-id="infoUrl">
					</div>
					`)
            $("input[name='infoUrl']").val(infoUrl.join(','));
        } else {
            layer.msg('上传的图片已达上限，请删除在传')
        }
    }
    closeUpload();
}

closeUpload();

function closeUpload() {

    // 删除图片
    $(".closeUpload").unbind("click");
    $(".closeUpload").click(function () {

        $(this).parents('.layui-inline').remove();
        let objId = $(this).attr('data-id');
        console.log(objId,$(this).attr('data-index'))

        if (objId == 'image') {
            image.splice($(this).attr('data-index'), 1);
            $("input[name='image']").val(image.join(','));
        }

        if (objId == 'picture') {
            picture.splice($(this).attr('data-index'), 1);
            $("input[name='picture']").val(picture.join(','));
        }

        if (objId == 'infoUrl') {
            infoUrl.splice($(this).attr('data-index'), 1);
            $("input[name='infoUrl']").val(infoUrl.join(','));
        }

    })

}
